# -*- encoding: utf-8 -*-
"""
@File ：product_lot
@Author ：Lucas
@Date ：2023-10-19 09:42
@Description: 
"""

import logging
from odoo import models, api, fields
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class ProductLot(models.Model):
    _log_access = False
    _name = 'justdoo.product.lot'
    _description = '产品批次'

    name = fields.Char(string='名称', index=True, required=True)
    product_id = fields.Integer('产品ID', index=True, required=True)
    product_code = fields.Char('产品编码', index=True, required=True)
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    company_name = fields.Char('公司', default=lambda self: self.env.company.name)
    company_id = fields.Integer('公司ID', default=lambda self: self.env.company.id)

    _sql_constraints = [('uniq_name', 'unique(name, product_id)', """批次已存在，请不要重复操作""")]

    @api.model_create_multi
    def create(self, value_list):
        for value in value_list:
            value['name'] = value['name'].strip()
        return super().create(value_list)

    @api.model
    def get_product_lot(self, product, lot_code, need_create=False):
        """ 获取产品批次信息，根据 need_create决定是否新建
            :param product: 产品
            :param lot_code: 产品批次
            :param need_create: 如果不存在是否新建
        """
        lot_domain = [('product_id', '=', product.id), ('name', '=', lot_code)]
        product_lot = self.env['justdoo.product.lot'].sudo().search(lot_domain, limit=1)
        if not product_lot and need_create:
            product_lot = self.env['justdoo.product.lot'].sudo().create({
                'name': lot_code, 'product_id': product.id, 'product_code': product.code
            })
        return product_lot


